#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/msg.h> 


struct msg_struct
{   
    long int   msg_type;  
    char       msg_text[BUFSIZ];
}msg_st; 




int main()
{   
    int                  starting = 1;    
    int                  msgid = -1;
    struct msg_struct    data;
    long int             msgtype = 0; //注意1     //建立消息队列    
   

    msgid = msgget((key_t)1234, 0666 | IPC_CREAT);  
    if(msgid <0 ) 
    {       
        printf("msgget failed with error: %d\n", errno);   
        return -1; 
    }  
   


    //从队列中获取消息，直到遇到end消息为止  
    while(starting)  
    {   
        if(msgrcv(msgid, (void*)&data, BUFSIZ, msgtype, 0) < 0)   
        {   
            printf("msgrcv failed with errno: %d\n", errno);   
            return -2;     
        }   
        printf("You wrote: %s\n",data.msg_text);     
     
        //遇到end结束   
        if(strncmp(data.msg_text, "end", 3) == 0)       
            starting = 0;    
    }  

     //删除消息队列    
    if(msgctl(msgid, IPC_RMID, 0) == -1)    
    {       
        printf("msgctl(IPC_RMID) failed\n");   
        return -3; 
    }   
    
    return 0;
}
